package com.guan.util;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 生成验证码的工具类
 * Created by Administrator on 2018/1/23 0023.
 */
public class ValidateCodeUtil {
    private static Random random = new Random();
    private static final String CODE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /**
     * 产生验证码图片
     * @param request
     * @return
     */
    public static BufferedImage getValidateCode(HttpServletRequest request){
        int width = 120,height = 36;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D grap = image.createGraphics();
        //设置画笔的颜色
        grap.setColor(randColor(180,255));
        //使用填充的方式，将整个背景填充为这个颜色
        grap.fillRect(0, 0, width, height);
        //先划线，在画验证码，清晰
        randLines(grap,width,height);
        String code = getRandomCode(4);
        //开始坐标
        int x = 10;
        //设置字体
        grap.setFont(new Font("微软雅黑",Font.BOLD,25));
        for(int i = 0 ;i<code.length();i++){
            grap.setColor(randColor(50,140));
            //验证码旋转的角度
            double degree = random.nextInt()%45*Math.PI/180;
            //旋转角度
            grap.rotate(degree,x,30);
            grap.drawString(code.charAt(i)+"", x, 30);
            grap.rotate(-degree,x,30);
            x+=30;
        }
        //验证码的值存储到当前会话中
        request.getSession().setAttribute("code", code);
        return  image;
    }
    /**
     * 获取四位数随机码
     * @param num
     * @return
     */
    public static String getRandomCode(int num){
        StringBuffer buffer = new StringBuffer();
        for(int i =0 ; i <num ; i++ ){
            buffer.append(CODE.charAt(random.nextInt(CODE.length())));
        }
        return buffer.toString();
    }

    /**
     * 产生随机干扰线
     * @param grap
     * @param widht
     * @param height
     */
    public static void randLines(Graphics2D grap, int widht, int height){
        for(int i = 0;i <40;i++){
            grap.setColor(randColor(150, 170));
            int x1 = random.nextInt(widht);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(widht);
            int y2 = random.nextInt(height);
            grap.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 产生随机颜色
     * @param start
     * @param end
     * @return
     */
    public static Color randColor(int start,int end){
        Random random = new Random();
        //0-255
        int red = start +(random.nextInt(end-start));
        int green=start +(random.nextInt(end-start));
        int blue=start +(random.nextInt(end-start));
        return new Color(red, green, blue);
    }
    public static void main(String[] args){
       System.out.print(getRandomCode(4));
    }
}
